package com.codefish.framework.spring.beans.factory.config;

import com.codefish.framework.spring.beans.factory.support.BeanDefinition;
import com.codefish.framework.spring.beans.factory.support.PropertyValue;
import com.codefish.framework.spring.util.IStringValueResolver;

import java.util.Properties;

/**
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/11/04 下午 06:29
 */
public class PropertyPlaceholderConfigurer extends PlaceholderConfigurerSupport {


    @Override
    protected void processProperties(Properties properties, IConfigurableListableBeanFactory beanFactory) {
        //处理beanFactory中所有的BeanDefinition
        for (String bdName : beanFactory.getBeanDefinitionNames()) {
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(bdName);
            doProcessProperties(properties, beanDefinition);
        }
    }

    protected void doProcessProperties(Properties properties, BeanDefinition bd) {
        for (PropertyValue propertyValue : bd.getPropertyValues()) {
            Object value = propertyValue.getValue();
            if (value instanceof String) {
                String val = (String) value;
                //属性占位替换成目标值
                propertyValue.setValue(resolveValue(properties, val));
            }
        }
    }

    @Override
    protected void addStringValueResolverIfNecessary(Properties properties, IConfigurableListableBeanFactory beanFactory) {
        //向BeanFactory添加字符串解析器
        beanFactory.addStringValueResolver(new PlaceholderStringValueResolver(properties));
    }

    /**
     * 属性字符串解析器
     */
    private class PlaceholderStringValueResolver implements IStringValueResolver {

        private final Properties properties;

        public PlaceholderStringValueResolver(Properties properties) {
            this.properties = properties;
        }

        @Override
        public String resolveStringValue(String strVal) {
            return resolveValue(properties, strVal);
        }
    }

}
